package com.bleeth.fx.component;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import com.bleeth.fx.helper.SStyleHelper;
import javafx.scene.layout.Region;
import javafx.scene.shape.SVGPath;
import lombok.Builder;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

@Builder
public class MSvg {

    private String path;

    private double width;

    private double height;

    private String color;

    public Region make() {
        Document document = XmlUtil.readXML(ResourceUtil.getStream(path));
        Node svgTag = document.getElementsByTagName("svg").item(0);
        String widthStr = svgTag.getAttributes().getNamedItem("width").getNodeValue();
        String heightStr = svgTag.getAttributes().getNamedItem("height").getNodeValue();
        if (width == 0) {
            width = Convert.toDouble(widthStr, 50D);
        }
        if (height == 0) {
            height = Convert.toDouble(heightStr, 50D);
        }

        Node pathTag = document.getElementsByTagName("path").item(0);
        String dStr = pathTag.getAttributes().getNamedItem("d").getNodeValue();
        String colorStr = pathTag.getAttributes().getNamedItem("fill").getNodeValue();

        SVGPath svg = new SVGPath();
        svg.setContent(dStr);

        Region box = new Region();
        box.setShape(svg);
        box.setPrefHeight(height);
        box.setPrefWidth(width);
        if (StrUtil.isNotEmpty(colorStr)) {
            SStyleHelper.node(box).addStyle("-fx-background-color", colorStr);
        }
        if (StrUtil.isNotEmpty(color)) {
            SStyleHelper.node(box).addStyle("-fx-background-color", color);
        }
        SStyleHelper.node(box).apply();
        return box;
    }


}
